package com.example.tianyutong.qanda.ui;

import android.arch.lifecycle.Observer;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

import com.example.tianyutong.qanda.R;
import com.example.tianyutong.qanda.app.ConstantsImageUrl;
import com.example.tianyutong.qanda.base.BaseActivity;
import com.example.tianyutong.qanda.bean.wanandroid.CoinUserInfoBean;
import com.example.tianyutong.qanda.data.UserUtil;
import com.example.tianyutong.qanda.databinding.ActivityMainBinding;
import com.example.tianyutong.qanda.databinding.NavHeaderMainBinding;
import com.example.tianyutong.qanda.databinding.AppBarMainBinding;
import com.example.tianyutong.qanda.http.rx.RxBus;
import com.example.tianyutong.qanda.http.rx.RxBusBaseMessage;
import com.example.tianyutong.qanda.http.rx.RxCodeConstants;
import com.example.tianyutong.qanda.ui.page_3.Fragment_sort;
import com.example.tianyutong.qanda.ui.page_2.Fragment_hot;
import com.example.tianyutong.qanda.ui.page_4.Fragment_me;
import com.example.tianyutong.qanda.ui.menu.NavAboutActivity;
import com.example.tianyutong.qanda.ui.menu.NavAdmireActivity;
import com.example.tianyutong.qanda.ui.menu.NavDeedBackActivity;
import com.example.tianyutong.qanda.ui.menu.NavDownloadActivity;
import com.example.tianyutong.qanda.ui.menu.NavHomePageActivity;
import com.example.tianyutong.qanda.ui.menu.SearchActivity;
import com.example.tianyutong.qanda.ui.page_1.Fragment_home;
import com.example.tianyutong.qanda.ui.menu.LoginActivity;
import com.example.tianyutong.qanda.ui.menu.MyCoinActivity;
import com.example.tianyutong.qanda.ui.menu.MyCollectActivity;
import com.example.tianyutong.qanda.ui.question_window.MoreWindow;
import com.example.tianyutong.qanda.utils.BaseTools;
import com.example.tianyutong.qanda.utils.CommonUtils;
import com.example.tianyutong.qanda.utils.DialogBuild;
import com.example.tianyutong.qanda.utils.GlideUtil;
import com.example.tianyutong.qanda.utils.PerfectClickListener;
import com.example.tianyutong.qanda.utils.SPUtils;
import com.example.tianyutong.qanda.utils.UpdateUtil;
import com.example.tianyutong.qanda.view.MyFragmentPagerAdapter;
import com.example.tianyutong.qanda.view.OnLoginListener;
import com.example.tianyutong.qanda.view.OnMyPageChangeListener;
import com.example.tianyutong.qanda.view.statusbar.StatusBarUtil;
import com.example.tianyutong.qanda.view.webview.WebViewActivity;
import com.example.tianyutong.qanda.viewmodel.wan.MainViewModel;

import java.util.ArrayList;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;


/**
 * Created by tianyutong on 16/11/21.
 *
 * <a href="https://github.com/youlookwhat">Follow me</a>
 * <a href="https://github.com/youlookwhat/CloudReader">source code</a>
 * <a href="http://www.jianshu.com/u/e43c6e979831">Contact me</a>
 */
public class MainActivity extends BaseActivity<MainViewModel, ActivityMainBinding> implements View.OnClickListener {

    public static boolean isLaunch;
    private ViewPager viewPagerContent;
    private ImageView imageView_2;
    private ImageView imageView_1;
    private ImageView imageView_3;
    private ImageView imageView_4;
    private FrameLayout question_button;
    ActionBar actionBar;
    private NavHeaderMainBinding navHeaderMainBinding;

    DrawerLayout drawerLayout;
    MoreWindow mMoreWindow;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//BaseActivity里的方法
        showContentView();//BaseActivity里定义的方法，关闭加载动画，显示页面
        isLaunch = true;
        initView();//设置顶栏
        initContentFragment();//设置底栏上三个tab
        initDrawerLayout();//侧栏
        initRxBus();
    }
    //设置状态栏
    @Override
    protected void initStatusBar() {
//        StatusBarUtil.setColorNoTranslucentForDrawerLayout(MainActivity.this, bindingView.drawerLayout, CommonUtils.getColor(R.color.colorTransparent));
//        ViewGroup.LayoutParams layoutParams = bindingView.include.viewStatus.getLayoutParams();
//        layoutParams.height = StatusBarUtil.getStatusBarHeight(this);
//        bindingView.include.viewStatus.setLayoutParams(layoutParams);
        //设置一个状态栏高度的占位栏
        StatusBarUtil.setRootViewFitsSystemWindows(this,true);
        //设置状态栏透明且不占位置
        StatusBarUtil.setTranslucentStatus(this);
        //一般的手机的状态栏文字和图标都是白色的, 可如果你的应用也是纯白色的, 或导致状态栏文字看不清
        //所以如果你是这种情况,请使用以下代码, 设置状态使用深色文字图标风格, 否则你可以选择性注释掉这个if内容
        if (!StatusBarUtil.setStatusBarDarkTheme(this, true)) {
            //如果不支持设置深色风格 为了兼容总不能让状态栏白白的看不清, 于是设置一个状态栏颜色为半透明,
            //这样半透明+白=灰, 状态栏的文字能看得清
            StatusBarUtil.setColor(this,000000,55);
        }
    }
    //设置顶栏
    private void initView() {
        setNoTitle();//设置无标题栏

        //bindingView是baseactivity里定义的实例化页面的binding类，
        // 这里是activity_main中include组件中的app_bar_main布局中id为toolbar的一个Toolbar布局
        setSupportActionBar(bindingView.include.toolbar);

        //这里是不显示导航栏的标题
        actionBar = getSupportActionBar();
        if (actionBar != null) {
            //去除默认Title显示
            actionBar.setDisplayShowTitleEnabled(false);
        }

//        //获取剪切板链接
//        getClipContent();
        //自定义类中自定义方法，用来检测更新
        UpdateUtil.check(this, false);
    }
    //初始化侧栏监听
    private void initDrawerLayout() {
        bindingView.navView.inflateHeaderView(R.layout.nav_header_main);//向activity_main中的navView组件中引入nav_header_main，inflateHeaderView 进来的布局要宽一些
        View headerView = bindingView.navView.getHeaderView(0);//获取nav_header_main的view
        navHeaderMainBinding = DataBindingUtil.bind(headerView);//绑定nav_header_main的binding对象
        navHeaderMainBinding.setViewModel(viewModel);
        navHeaderMainBinding.dayNightSwitch.setChecked(SPUtils.getNightMode());
        viewModel.isReadOk.set(SPUtils.isRead());

        GlideUtil.displayCircle(navHeaderMainBinding.ivAvatar, ConstantsImageUrl.IC_AVATAR);
        navHeaderMainBinding.llNavExit.setOnClickListener(this);
        navHeaderMainBinding.ivAvatar.setOnClickListener(this);

        navHeaderMainBinding.llNavHomepage.setOnClickListener(listener);
        navHeaderMainBinding.llNavScanDownload.setOnClickListener(listener);
        navHeaderMainBinding.llNavDeedback.setOnClickListener(listener);
        navHeaderMainBinding.llNavAbout.setOnClickListener(listener);
        navHeaderMainBinding.llNavLogin.setOnClickListener(listener);
        navHeaderMainBinding.llNavCollect.setOnClickListener(listener);
        navHeaderMainBinding.llInfo.setOnClickListener(listener);
        navHeaderMainBinding.llNavCoin.setOnClickListener(listener);
        navHeaderMainBinding.llNavAdmire.setOnClickListener(listener);
        navHeaderMainBinding.tvRank.setOnClickListener(listener);

        viewModel.getUserInfo();
        viewModel.getCoin().observe(this, new Observer<CoinUserInfoBean>() {
            @Override
            public void onChanged(@Nullable CoinUserInfoBean coinUserInfoBean) {
                if (coinUserInfoBean != null) {
                    //设置用户名，等级，排名
                    navHeaderMainBinding.tvUsername.setText(coinUserInfoBean.getUsername());
                    navHeaderMainBinding.tvLevel.setText(String.format("Lv.%s", UserUtil.getLevel(coinUserInfoBean.getCoinCount())));
                    navHeaderMainBinding.tvRank.setText(String.format("排名 %s", coinUserInfoBean.getRank()));
                } else {
                    navHeaderMainBinding.tvUsername.setText("玩安卓登录");
                    navHeaderMainBinding.tvLevel.setText("Lv.1");
                    navHeaderMainBinding.tvRank.setText("");
                }
            }
        });
    }
    //初始化主界面各个按钮并监听
    private void initContentFragment() {
        drawerLayout=findViewById(R.id.drawer_layout);
        mMoreWindow = new MoreWindow(this);
        mMoreWindow.init(drawerLayout,this);

        viewPagerContent = bindingView.include.vpContent;//viewpage
        imageView_1 = bindingView.include.ivTitleOne;
        imageView_2 = bindingView.include.ivTitleTwo;
        imageView_3 = bindingView.include.ivTitleThree;
        imageView_4 = bindingView.include.ivTitleFour;
        question_button=bindingView.include.mainBtn;
        //这些都是app_bar_main布局中的底栏组件,监听点击事件，后面有重写的onClick()
        bindingView.include.llTitleMenu.setOnClickListener(this);//侧栏菜单
        bindingView.include.ivTitleOne.setOnClickListener(this);
        bindingView.include.ivTitleTwo.setOnClickListener(this);
        bindingView.include.ivTitleThree.setOnClickListener(this);
        bindingView.include.ivTitleFour.setOnClickListener(this);
        bindingView.include.mainBtn.setOnClickListener(this);
        ArrayList<Fragment> mFragmentList = new ArrayList<>();
        mFragmentList.add(new Fragment_home());//ui\wan\WanFragment.java
        mFragmentList.add(new Fragment_hot());//ui\gank\GankFragment.java
        mFragmentList.add(new Fragment_sort());//ui\film\FilmFragment.java
        mFragmentList.add(new Fragment_me());
        // 注意使用的是：getSupportFragmentManager,MyFragmentPagerAdapter目录view\MyFragmentPagerAdapter.java
        MyFragmentPagerAdapter adapter = new MyFragmentPagerAdapter(getSupportFragmentManager(), mFragmentList);
        viewPagerContent.setAdapter(adapter);
        // 设置ViewPager最大缓存的页面个数(cpu消耗少)
        viewPagerContent.setOffscreenPageLimit(3);
        //监听手指滑动页面改变，点击页面改变在后面重写的onClick()
        viewPagerContent.addOnPageChangeListener(new OnMyPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                switch (position) {
                    case 0:
                        setCurrentItem(0);//自定义方法
                        break;
                    case 1:
                        setCurrentItem(1);
                        break;
                    case 2:
                        setCurrentItem(2);
                        break;
                    case 3:
                        setCurrentItem(3);
                        break;
                    default:
                        break;
                }
            }
        });
        setCurrentItem(0);//什么都不按时候默认显示第一个页面
    }

    //侧栏设置监听事件
    private PerfectClickListener listener = new PerfectClickListener() {
        @Override
        protected void onNoDoubleClick(final View v) {
            bindingView.drawerLayout.closeDrawer(GravityCompat.START);
            bindingView.drawerLayout.postDelayed(() -> {
                switch (v.getId()) {
                    case R.id.ll_nav_homepage:
                        // 主页
                        NavHomePageActivity.startHome(MainActivity.this);
                        break;
                    case R.id.ll_nav_scan_download:
                        //扫码下载
                        NavDownloadActivity.start(MainActivity.this);
                        break;
                    case R.id.ll_nav_deedback:
                        // 问题反馈
                        NavDeedBackActivity.start(MainActivity.this);
                        if (viewModel.isReadOk.get() != null && !viewModel.isReadOk.get().booleanValue()) {
                            SPUtils.setRead(true);
                            viewModel.isReadOk.set(true);
                        }
                        break;
                    case R.id.ll_nav_about:
                        // 关于云阅
                        NavAboutActivity.start(MainActivity.this);
                        break;
                    case R.id.ll_nav_collect:
                        // 玩安卓收藏
                        if (UserUtil.isLogin(MainActivity.this)) {
                            MyCollectActivity.start(MainActivity.this);
                        }
                        break;
                    case R.id.ll_nav_login:
                        // 玩安卓登录
                        DialogBuild.showItems(v, new OnLoginListener() {
                            @Override
                            public void loginWanAndroid() {
                                LoginActivity.start(MainActivity.this);
                            }

                            @Override
                            public void loginGitHub() {
                                WebViewActivity.loadUrl(v.getContext(), "https://github.com/login", "登录GitHub账号");
                            }
                        });
                        break;
                    case R.id.ll_info:
                        // 登录
                        if (!UserUtil.isLogin()) {
                            LoginActivity.start(MainActivity.this);
                        } else {
                            MyCoinActivity.start(MainActivity.this);
                        }
                        break;
                    case R.id.ll_nav_coin:
                        // 我的积分
                        if (UserUtil.isLogin(MainActivity.this)) {
                            MyCoinActivity.start(MainActivity.this);
                        }
                        break;
                    case R.id.tv_rank:
                        // 排行
                        if (UserUtil.isLogin(MainActivity.this)) {
                            MyCoinActivity.startRank(MainActivity.this);
                        }
                        break;
                    case R.id.ll_nav_admire:
                        // 赞赏
                        NavAdmireActivity.start(MainActivity.this);
                        break;
                    default:
                        break;
                }
            }, 260);
        }
    };
    //activity_main界面的点击监听事件
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_title_menu:
                // 开启菜单
                bindingView.drawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.iv_title_two:
                // 不然cpu会有损耗
                if (viewPagerContent.getCurrentItem() != 1) {
                    setCurrentItem(1);
                }
                break;
            case R.id.iv_title_one:
                if (viewPagerContent.getCurrentItem() != 0) {
                    setCurrentItem(0);
                }
                break;
            case R.id.iv_title_three:
                if (viewPagerContent.getCurrentItem() != 2) {
                    setCurrentItem(2);
                }
                break;
            case R.id.iv_title_four:
                if (viewPagerContent.getCurrentItem() != 3) {
                    setCurrentItem(3);
                }
                break;
            case R.id.mainBtn:
                showMoreWindow();
                break;
            case R.id.iv_avatar:
                // 头像进入GitHub
                WebViewActivity.loadUrl(v.getContext(), CommonUtils.getString(R.string.string_url_cloudreader), "CloudReader");
                break;
            case R.id.ll_nav_exit:
                // 退出应用
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 切换页面和图片状态
     *
     * @param position 分类角标
     */
    private void setCurrentItem(int position) {
        boolean isOne = false;
        boolean isTwo = false;
        boolean isThree = false;
        boolean isFour = false;
        switch (position) {
            case 0:
                isOne = true;
                actionBar.show();
                break;
            case 1:
                isTwo = true;
                actionBar.show();
                break;
            case 2:
                isThree = true;
                actionBar.show();
                break;
            case 3:
                isFour = true;
                actionBar.hide();
                break;
        }
        viewPagerContent.setCurrentItem(position);//切换页面
        imageView_1.setSelected(isOne);//这里是ImageView切换被选中的图片，imageView_1.setSelected(true)时显示navbar_home.xml中为true的图片
        imageView_2.setSelected(isTwo);
        imageView_3.setSelected(isThree);
        imageView_4.setSelected(isFour);
    }
    private void showMoreWindow() {
        if (null == mMoreWindow) {
            mMoreWindow = new MoreWindow(this);
            mMoreWindow.init(drawerLayout,this);
        }

        mMoreWindow.showMoreWindow(drawerLayout);
    }
    /**
     * 夜间模式待完善
     */
    public boolean getNightMode() {
        return SPUtils.getNightMode();
    }

    public void onNightModeClick(View view) {
        if (!SPUtils.getNightMode()) {
//            SkinCompatManager.getInstance().loadSkin(Constants.NIGHT_SKIN);
        } else {
            // 恢复应用默认皮肤
//            SkinCompatManager.getInstance().restoreDefaultTheme();
        }
        SPUtils.setNightMode(!SPUtils.getNightMode());
        navHeaderMainBinding.dayNightSwitch.setChecked(SPUtils.getNightMode());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    //启动搜索页面
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.action_search) {
            SearchActivity.start(this);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }



    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1) {
            getResources();
        }
    }

    /**
     * 禁止改变字体大小
     */
    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config = new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config, res.getDisplayMetrics());
        return res;
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (bindingView.drawerLayout.isDrawerOpen(GravityCompat.START)) {
                bindingView.drawerLayout.closeDrawer(GravityCompat.START);
            } else {
                // 不退出程序，进入后台
                moveTaskToBack(true);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 每日推荐点击"新电影热映榜"跳转
     */
    private void initRxBus() {
        Disposable subscribe = RxBus.getDefault().toObservable(RxCodeConstants.JUMP_TYPE_TO_ONE, RxBusBaseMessage.class)
                .subscribe(new Consumer<RxBusBaseMessage>() {
                    @Override
                    public void accept(RxBusBaseMessage rxBusBaseMessage) throws Exception {
                        setCurrentItem(2);
                    }
                });
        addSubscription(subscribe);
        Disposable subscribe2 = RxBus.getDefault().toObservable(RxCodeConstants.LOGIN, Boolean.class)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean isLogin) throws Exception {
                        if (isLogin) {
                            viewModel.getUserInfo();
                        } else {
                            viewModel.getCoin().setValue(null);
                        }
                    }
                });
        addSubscription(subscribe2);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isLaunch = false;
        // 杀死该应用进程 需要权限
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    public static void start(Context context) {
        context.startActivity(new Intent(context, MainActivity.class));
    }
}
